package cn.edu.dlut.ssdut.foodCredit2012.service;

/*import java.util.List;

import org.hibernate.Query;*/
import org.hibernate.Session;

import cn.edu.dlut.ssdut.foodCredit2012.model.Tax;
import cn.edu.dlut.ssdut.foodCredit2012.model.TaxCollection;
import cn.edu.dlut.ssdut.foodCredit2012.util.HibernateUtil;

public class TaxService {
	
	public void add(Tax t) throws Exception{
		if(!hasTax(t)){
			Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.save(t);
			session.getTransaction().commit();
		}
	}
	
	public void delete(Tax t) throws Exception {
		if(hasTax(t)){
			Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.delete(t);
			session.getTransaction().commit();
		}
	}
	
	public void update (Tax t) throws Exception {
		if(hasTax(t)){
			Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.update(t);
			session.getTransaction().commit();
		}
	}
	
	/*public List taxList() {
		List taxList = null;
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Query query = session.createQuery("from Tax");
		query.setFirstResult(2);
		query.setMaxResults(10);
		taxList = query.list();
		
		session.getTransaction().commit();
		
		return taxList;
	}*/
	
	public boolean hasTax(Tax t) throws Exception {
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		long count = (Long)session.createQuery("select count(*) from Tax t where t.licenceID = :licenceID")
			.setString("licenceID", t.getLicenceID())
			.uniqueResult();
		session.getTransaction().commit();
		
		if(count > 0) return true;
		return false;
		
	}
	
	public Tax load (Tax t)throws Exception{
		if(hasTax(t))
		{
			t = loadByLicenceID(t.getLicenceID());
			return t;
		}
		return t;
	}
	
	public Tax loadByLicenceID(String licenceID) throws Exception{
		Tax t = new Tax();
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		t = (Tax)session.createQuery("select t from Tax t where t.licenceID = :licenceID")
			.setParameter("licenceID", licenceID)
			.uniqueResult();
		session.getTransaction().commit();
		return t;
	}
	
	public Tax taxCollectionToTax(TaxCollection taxC) throws Exception{
		Tax t = new Tax();
		
		t.setChangeDate(taxC.getChangeDate());
		t.setLicenceID(taxC.getLicenceID());
		t.setName(taxC.getName());
		t.setTaxID(taxC.getTaxID());
		t.setTaxChange(taxC.getTaxChange());
		
		return t;
	}

}
